package com.atguigu.distributed.lock.leecode;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyData{
    volatile int number = 0;
    public void add(){
        this.number = 60;
    }
    public void addPlus(){
        number++;
    }
    AtomicInteger atomicInteger = new AtomicInteger();
    public void addAtoMic(){
        atomicInteger.getAndIncrement();
    }
}

public class VolatileTest {
    public static void main(String[] args) {
        //testVolatile();
        MyData myData = new MyData();
        for (int i = 1; i <= 20; i++) {
            new Thread(() -> {
                for (int j = 1; j <= 1000; j++) {
                    myData.addPlus();
                    myData.addAtoMic();
                }

            },String.valueOf(i)).start();
        }
        while(Thread.activeCount()>2){
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName()+"\t finally number value: "+myData.number);
        System.out.println(Thread.currentThread().getName()+"\t finally atoMic value: "+myData.atomicInteger.intValue());


    }

    public static void testVolatile() {
        MyData myData = new MyData();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                myData.add();
                System.out.println(Thread.currentThread().getName()+"\t update number value:"+myData.number);

            }
        },"AAAA").start();
        while (myData.number==0){

        }
        System.out.println(Thread.currentThread().getName()+"\t mission is over,main get number value:"+myData.number);
    }
}
